package controller

import (
	"context"
	"demo_bff/pkg"
	"demo_bff/user_proto"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func UserLogin(c *gin.Context) {
	mobile := c.PostForm("mobile")
	password := c.PostForm("password")
	captcha := c.PostForm("captcha")
	captchaId := c.PostForm("captcha_id")
	if mobile == "" || password == "" || captcha == "" || captchaId == "" {
		c.JSON(http.StatusNotFound, gin.H{
			"code": 0,
			"msg":  "参数不能为空",
			"data": nil,
		})
		return
	}
	comment := pkg.Comment()
	byMobile, err := comment.GetUserByMobile(context.Background(), &user_proto.GetUserByMobileRequest{Mobile: mobile})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	checkPassword, err := comment.CheckPassword(context.Background(), &user_proto.CheckPasswordRequest{
		Password:          password,
		EncryptedPassword: byMobile.Password,
	})
	if !checkPassword.Success {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}
	verify := store.Verify(captchaId, captcha, true)
	if !verify {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "图形验证码错误",
			"data": nil,
		})
		return
	}
	token, err := pkg.SetJwtToken(strconv.FormatInt(byMobile.Id, 10))
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "登录成功",
		"data": token,
	})
}
